package com.csdj.server.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.csdj.server.pojo.*;
import com.csdj.server.service.*;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ZouLi
 * @since 2022-12-12
 */
@RestController
@RequestMapping("/employee/basic")
public class EmployeeController {
    /**
     * 注入 EmployeeService
     **/
    @Autowired
    private IEmployeeService employeeServiceImpl;

    @Autowired
    private INationService nationService;
    @Autowired
    private IPoliticsStatusService politicsStatusService;
    @Autowired
    private IJoblevelService joblevelService;
    @Autowired
    private IPositionService positionService;
    @Autowired
    private IDepartmentService departmentService;

    @ApiOperation(value = "分页查询员工信息")
    @GetMapping("/getEmployeeByPage")
    public RespPageBean getEmployeeByPage(@RequestParam(defaultValue = "1") Integer page,
                                          @RequestParam(defaultValue = "10") Integer limit,
                                          Employee employee, LocalDate[] beginDateScope){

        return employeeServiceImpl.getEmployeeByPage(page, limit, employee, beginDateScope);
    }

    @ApiOperation(value = "获取最大工号")
    @GetMapping("/getMaxWorkID")
    public RespBean getMaxWorkID(){
        return employeeServiceImpl.getMaxWorkId();
    }

    @ApiOperation(value = "添加员工信息")
    @PostMapping("/saveEmployee")
    public RespBean saveEmployee(@RequestBody Employee employee){
        return employeeServiceImpl.insetEmployee(employee);
    }

    @ApiOperation(value = "修改员工信息")
    @PutMapping("/updateEmployee")
    public RespBean updateEmployee(@RequestBody Employee employee){
        if (employeeServiceImpl.updateById(employee)){
            return RespBean.success("修改成功！");
        }
        return RespBean.error("修改失败！");
    }

    @ApiOperation(value = "删除员工信息")
    @DeleteMapping("/deleteEmployee/{id}")
    public RespBean deleteEmployee(@PathVariable Integer id){
        if (employeeServiceImpl.removeById(id)) {
            return RespBean.success("删除成功！");
        }
        return RespBean.error("删除失败！");
    }

    @ApiOperation(value = "导出员工数据")
    @GetMapping(value = "/exportEmployee", produces= "application/octet-stream")
    public void exportEmployee(HttpServletResponse response){
        List<Employee> employeeList = employeeServiceImpl.getEmployeeById(null);
        // 创建导出所需参数
        ExportParams params = new ExportParams("员工表", "员工表", ExcelType.HSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(params, Employee.class, employeeList);

        ServletOutputStream out = null;
        try {
            response.setHeader("content-type","application/octet-stream");
            //防止中文乱码
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode("员工表.xls","UTF-8"));
            out = response.getOutputStream();
            workbook.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (out != null){
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @ApiOperation(value = "导入员工数据")
    @ApiImplicitParams({@ApiImplicitParam(name = "file", value = "上传文件", dataType = "MultipartFile")})
    @PostMapping("/importEmployee")
    public RespBean importEmployee(MultipartFile file){
        ImportParams importParams = new ImportParams();
        // 去掉标题行
        importParams.setTitleRows(1);
        // 获取列值
        List<Nation> nations = nationService.list();
        List<PoliticsStatus> politicsStatuses = politicsStatusService.list();
        List<Department> departments = departmentService.list();
        List<Joblevel> joblevels = joblevelService.list();
        List<Position> positions = positionService.list();

        try {
            List<Employee> importExcel = ExcelImportUtil.importExcel(file.getInputStream(), Employee.class, importParams);
            importExcel.forEach(employee -> {
                // 设置民族Id
                employee.setNationId(nations.get(nations.indexOf(new Nation(employee.getNation().getName()))).getId());
                // 设置政治面貌Id
                employee.setPoliticId(politicsStatuses.get(politicsStatuses.indexOf(new PoliticsStatus(employee.getPoliticsStatus().getName()))).getId());
                // 设置部门Id
                employee.setDepartmentId(departments.get(departments.indexOf(new Department(employee.getDepartment().getName()))).getId());
                // 设置职称Id
                employee.setJobLevelId(joblevels.get(joblevels.indexOf(new Joblevel(employee.getJoblevel().getName()))).getId());
                // 设置职位Id
                employee.setPosId(positions.get(positions.indexOf(new Position(employee.getPosition().getName()))).getId());
            });
            if (employeeServiceImpl.saveBatch(importExcel)){
                return RespBean.success("导入成功！");
            }
            return RespBean.error("导入失败！");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RespBean.error("导入失败！");
    }
}
